package com.yuantu.judiciary.common;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * Map与JSON映射转换器
 *
 * @author syw
 * @since 2023-07-19
 **/
@Converter
@RequiredArgsConstructor
public class MapAndJson implements AttributeConverter<Map<String, Object>, String> {

    private final ObjectMapper mapper;

    /**
     * 转换成数据库字段
     */
    @Override
    public String convertToDatabaseColumn(Map<String, Object> stringObjectMap) {
        try {
            return mapper.writeValueAsString(stringObjectMap);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 转换成实体字段
     */
    @Override
    @SuppressWarnings("unchecked")
    public Map<String, Object> convertToEntityAttribute(String s) {
        try {
            return mapper.readValue(s, HashMap.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return Collections.emptyMap();
    }

}
